/* ---------------------------------------------------------------- FONCTIONS */
/**
 * Détermine si une variable est NULL ou vide.
 */
function isNullOrEmpty(v) {
	if(v != null && v != "")
		return false;
	else
		return true;
}

/**
 * Détermine la taille (nombre d'éléments) d'un objet.
 */
function objectLength(o) {
	var r = 0;
	for(var p in o) {
		if(o.hasOwnProperty(p))
			r++;
	}
	return r;
};



/* ----------------------------------------------------------- INITIALISATION */
$(function() {
	$("#home_h3_span_1").tooltip();
	$("#home_h3_span_2").tooltip();
});



/**
 * Déconnexion de l'utilisateur.
 */
$(function() {
	$("#a_logout").on("click", function() {
		logout();
	});
	
	// TODO TEST A RETIRER
	$("#a_test_add_challenge").on("click", function() {
		$.ajax({
			url: "page/test_add_challenge.jsp",
			async: false,
			dataType: "html",
			type: "get",
			error: function(xhr, ajaxOptions, thrownError) {
				alert("Erreur ajout défi\n" + xhr.status + "\n" + thrownError);
			},
			success: function(content) {
				window.location.reload(true);
			}
		});
	});
});



/**
 * Interception des soumissions des formulaires.
 */
$(function() {
	/**
	 * Connexion.
	 */
	$("#form_login").on("submit", function() {
		return form_login();
	});
	
	/**
	 * Inscription.
	 */
	$("#form_subscribe").on("submit", function() {
		return form_subscribe();
	});
	
	$("#form_search_train").on("submit", function() {
		form_search_train();
		
		return false;
	});
	
	/**
	 * Recherche d'utilisateurs.
	 */
	$("#form_search_user").on("submit", function() {
		form_search_user();
		
		return false;
	});
});



/**
 * Affichage du contenu des tables au chargement de la page.
 */
$(function() {
	if($("#table_home_ratio").length > 0){
		top_ten_ratio();
	}
	if($("#table_home_score").length > 0){
		top_ten_score();
	}

	if($("#form_search_train").length > 0) {
		search_train($("#form_search_user_pseudo").val());
	}

	if($("#table_challenges").length > 0) {
		challenges();
	}

	if($("#table_friends").length > 0) {
		friends($("#table_friends").attr("data-user_id"));
	}

	if($("#table_bets").length > 0 || $("#table_bets_history").length > 0) {
		bets();
	}
});



/* -------------------------------------------------------------- FORMULAIRES */
/* CONNEXION ---------------------------------------------------------------- */
/**
 * Validation et envoi du formulaire de connexion.
 */
function form_login() {
	form_login_clean();
	var regex_mail = new RegExp('^[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');
	
	// présence du mail
	if(!isNullOrEmpty($("#form_login_mail").val())) {
		// validité du mail (l'input étant de type "email", html5 le vérifie mais avec des contraintes moins fortes)
		if(regex_mail.test($("#form_login_mail").val())) {
			// présence du mot de passe
			if(!isNullOrEmpty($("#form_login_password").val())) {
				// erreur lors de connexion
				if(!form_login_send($("#form_login_mail").val(), md5($("#form_login_password").val()))) {
					$("#form_login_help").html("<strong class=\"text-danger\">Informations de connexion incorrectes.</strong>");
				}
			}
			else {
				$("#form_login_password").parent().addClass("has-error");
				$("#form_login_help").html("<strong class=\"text-danger\">Mot de passe non renseigné.</strong>");
			}
		}
		else {
			$("#form_login_mail").parent().addClass("has-error");
			$("#form_login_help").html("<strong class=\"text-danger\">Adresse mail non valide.</strong>");
		}
	}
	else {
		$("#form_login_mail").parent().addClass("has-error");
		$("#form_login_help").html("<strong class=\"text-danger\">Adresse mail non renseignée.</strong>");
	}
	
	return false;
}

/**
 * Nettoyage du CSS du formulaire de connexion.
 */
function form_login_clean() {
	$("#form_login_mail").parent().removeClass("has-error has-success");
	$("#form_login_password").parent().removeClass("has-error has-success");
	$("#form_login_help").html("");
	
	return true;
}

/**
 * Envoi du formulaire de connexion.
 */
function form_login_send(mail, password) {
	$.ajax({
		url: "S_Login",
		async: false,
		data: {
			mail: mail,
			password: password
		},
		dataType: "html",
		type: "post",
		error: function(xhr, ajaxOptions, thrownError) {
			console.error("Erreur connexion\n" + xhr.status + "\n" + thrownError);
			// si la BD ne connait pas le couple (mail, password)
			if(xhr.status == 599) {
				return false;
			}
		},
		success: function() {
			var href = window.location.href.split("/");
			var url = "";
			for(var i = 0, i_max = href.length - 1; i < i_max; i++) {
				url += href[i] + "/";
			}
			window.location.href = url;
		}
	});
}



/* INSCRIPTION -------------------------------------------------------------- */
/**
 * Validation du formulaire d'inscription.
 */
function form_subscribe() {
	form_subscribe_clean();
	var regex_mail = new RegExp('^[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*@[a-z0-9]+([_|\.|-]{1}[a-z0-9]+)*[\.]{1}[a-z]{2,6}$', 'i');
	
	// présence du mail
	if(!isNullOrEmpty($("#form_subscribe_mail").val())) {
		// validité du mail (l'input étant de type "email", html5 le vérifie mais avec des contraintes moins fortes)
		if(regex_mail.test($("#form_subscribe_mail").val())) {
			// présence du pseudo
			if(!isNullOrEmpty($("#form_subscribe_pseudo").val())) {
				// présence du mot de passe
				if(!isNullOrEmpty($("#form_subscribe_password").val())) {
					// présence de la confirmation du mot de passe
					if(!isNullOrEmpty($("#form_subscribe_password_2").val())) {
						// comparaison des deux mots de passe
						if($("#form_subscribe_password").val() == $("#form_subscribe_password_2").val()) {
							// erreur lors de l'inscription
							if(!form_subscribe_send($("#form_subscribe_mail").val(), $("#form_subscribe_pseudo").val(), md5($("#form_subscribe_password").val()))) {
								$("#form_subscribe_help").html("<strong class=\"text-danger\">Inscription impossible, cette adresse mail est déjà utilisée.</strong>");
							}
						}
						else {
							$("#form_subscribe_help").html("<strong class=\"text-danger\">Les deux mots de passe ne correspondent pas.</strong>");
							$("#form_subscribe_password").parent().addClass("has-error");
							$("#form_subscribe_password_2").parent().addClass("has-error");
						}
					}
					else {
						$("#form_subscribe_help").html("<strong class=\"text-danger\">Confirmation du mot de passe non renseignée.</strong>");
						$("#form_subscribe_password_2").parent().addClass("has-error");
					}
				}
				else {
					$("#form_subscribe_help").html("<strong class=\"text-danger\">Mot de passe non renseigné.</strong>");
					$("#form_subscribe_password").parent().addClass("has-error");
				}
			}
			else {
				$("#form_subscribe_help").html("<strong class=\"text-danger\">Pseudo non renseigné.</strong>");
				$("#form_subscribe_pseudo").parent().addClass("has-error");
			}
		}
		else {
			$("#form_subscribe_help").html("<strong class=\"text-danger\">Adresse mail non valide.</strong>");
			$("#form_subscribe_mail").parent().addClass("has-error");
		}
	}
	else {
		$("#form_subscribe_help").html("<strong class=\"text-danger\">Adresse mail non renseignée.</strong>");
		$("#form_subscribe_mail").parent().addClass("has-error");
	}
	
	return false;
}

/**
 * Nettoyage du CSS du formulaire d'inscription.
 */
function form_subscribe_clean() {
	$("#form_subscribe_mail").parent().removeClass("has-error has-success");
	$("#form_subscribe_pseudo").parent().removeClass("has-error has-success");
	$("#form_subscribe_password").parent().removeClass("has-error has-success");
	$("#form_subscribe_password_2").parent().removeClass("has-error has-success");
	$("#form_subscribe_help").html("");
	
	return true;
}

/**
 * Envoi du formulaire d'inscription.
 */
function form_subscribe_send(mail, pseudo, password) {
	$.ajax({
		url: "S_Subscribe",
		async: false,
		data: {
			mail: mail,
			pseudo: pseudo,
			password: password
		},
		dataType: "html",
		type: "post",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Erreur inscription\n" + xhr.status + "\n" + thrownError);
			// si le mail est déjà utilisé
			if(xhr.status == 599) {
				return false;
			}
		},
		success: function() {
			var href = window.location.href.split("/");
			var url = "";
			for(var i = 0, i_max = href.length - 1; i < i_max; i++) {
				url += href[i] + "/";
			}
			window.location.href = url;
		}
	});
}



/* DECONNEXION -------------------------------------------------------------- */
/**
 * Déconnexion.
 */
function logout() {
	$.ajax({
		url: "S_Logout",
		async: false,
		dataType: "html",
		type: "post",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Erreur déconnexion\n" + xhr.status + "\n" + thrownError);
		},
		success: function() {
			var href = window.location.href.split("/");
			var url = "";
			for(var i = 0, i_max = href.length - 1; i < i_max; i++) {
				url += href[i] + "/";
			}
			window.location.href = url;
		}
	});
}



/* --------------------------------------------------- RECHERCHE ET AFFICHAGE */
/* HOME --------------------------------------------------------------------- */
/**
 * Recherche les utilisateurs ayant le meilleur ratio.
 */
function top_ten_ratio() {
	$.ajax({
		url: "S_TopTenRatio",
		async: true,
		dataType: "json",
		type: "post",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Erreur meilleurs ratio\n" + xhr.status + "\n" + thrownError);
		},
		success: function(content) {
			top_ten_ratio_display(content);
		}
	});
}

/**
 * Affiche les utilisateurs ayant le meilleur ratio.
 */
function top_ten_ratio_display(json_data) {
	// TODO
	var html = "";
	for(i = 0, i_max = objectLength(json_data["@items"]); i < i_max; i++) {
		html += "<tr>"
			+ "<td>" + (i + 1) +"</span></td>"
			+ "<td>" + json_data["@items"][i]["pseudo"] + "</td>"
			+ "<td>" + json_data["@items"][i]["score"] + "</td>"
			+ "<td>" + (json_data["@items"][i]["ratio"] * 100).toFixed(2) + " %</td>"
			+ "</tr>";
	}
	$("#table_home_ratio>tbody").html(html);
}



/**
 * Recherche les utilisateurs ayant le meilleur score.
 */
function top_ten_score() {
	$.ajax({
		url: "S_TopTenScore",
		async: true,
		dataType: "json",
		type: "post",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Erreur meilleurs score\n" + xhr.status + "\n" + thrownError);
		},
		success: function(content) {
			top_ten_score_display(content);
		}
	});
}

/**
 * Affiche les utilisateurs ayant le meilleur score.
 */
function top_ten_score_display(json_data) {
	var html = "";
	for(i = 0, i_max = objectLength(json_data["@items"]); i < i_max; i++) {
		html += "<tr>"
			+ "<td>" + (i + 1) +"</span></td>"
			+ "<td>" + json_data["@items"][i]["pseudo"] + "</td>"
			+ "<td>" + json_data["@items"][i]["score"] + "</td>"
			+ "<td>" + (json_data["@items"][i]["ratio"] * 100).toFixed(2) + " %</td>"
			+ "</tr>";
	}
	$("#table_home_score>tbody").html(html);
}















/* PARIS -------------------------------------------------------------------- */
/**
 * Recherche les paris de l'utilisateur.
 */
function bets(id_user) {
	$.ajax({
		url: "S_Bets",
		async: true,
		dataType: "json",
		type: "post",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Erreur bets\n" + xhr.status + "\n" + thrownError);
		},
		success: function(content) {
			bets_display(content);
		}
	});
	
	return false;
}

/**
 * Affiche les paris d'un utilisateur.
 */
function bets_display(json_data) {
	var html = "";
	for(i = 0, i_max = objectLength(json_data["bets"]); i < i_max; i++) {
		html += "<tr>"
			+ "<td>" + json_data["bets"][i]["gare"] + "</td>"
			+ "<td>" + json_data["bets"][i]["train"] + "<br/>" + json_data["bets"][i]["destination"] + "</td>"
			+ "<td>" + json_data["bets"][i]["heure"] + "</td>"
			+ "<td>" + json_data["bets"][i]["mise"] + " points sur " + json_data["bets"][i]["retard"] + "min<br/>Gain potentiel : " + json_data["bets"][i]["gain"] + " points</td>"
			+ "<td>";
		
		$.ajax({
			url: "form/form_new_challenge.jsp",
			async: false,
			data: {
				id_bet: json_data["bets"][i]["id_pari"]
			},
			dataType: "html",
			type: "get",
			error: function(xhr, ajaxOptions, thrownError) {
				alert("error bets_display\n" + xhr.status + "\n" + thrownError);
			},
			success: function(content) {
				html += content;
			}
		});
		
		html += "</td></tr>";
	}
	$("#table_bets>tbody").html(html);

	html = "";
	for(i = 0, i_max = objectLength(json_data["bets_history"]); i < i_max; i++) {
		html += "<tr class=\"" + (json_data["bets_history"][i]["reussi"] ? "success" : "danger") + "\">"
			+ "<td>" + json_data["bets_history"][i]["gare"] + "</td>"
			+ "<td>" + json_data["bets_history"][i]["train"] + "<br/>" + json_data["bets_history"][i]["destination"] + "</td>"
			+ "<td>" + json_data["bets_history"][i]["heure"] + "</td>"
			+ "<td>" + json_data["bets_history"][i]["mise"] + " points sur " + json_data["bets_history"][i]["retard"] + "min<br/>" + (json_data["bets_history"][i]["reussi"] ? "Gain : " + json_data["bets_history"][i]["gain"] + " points" : "") + "</td>"
			+ "</tr>";
	}
	$("#table_bets_history>tbody").html(html);
	
	return true;
}








/* RECHERCHE DES PROCHAINS TRAINS D'UNE GARE -------------------------------- */
/**
 * Recherche les prochains trains au passage d'une gare.
 */
function form_search_train() {
	$.ajax({
		url: "S_SearchTrain",
		async: true,
		data: {
			station_uic: $("#form_search_train_station_uic").val()
		},
		dataType: "json",
		type: "post",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Erreur recherche des prochains trains\n" + xhr.status + "\n" + thrownError);
		},
		success: function(content) {
			form_search_train_display(content);
		}
	});
	
	return false;
}

/**
 * Affiche les prochains trains d'une gare.
 */
function form_search_train_display(json_data) {
	//TODO
	alert(json_data);
	/*var html = "";
	for(i = 0, i_max = objectLength(json_data); i < i_max; i++) {
		html += "<tr class=\"clickable\" data-toggle=\"collapse\" data-target=\"#tr_form_new_bet_" + i + "\">"
			+ "<td><span class=\"glyphicon glyphicon-chevron-right\"></span></td>"
			+ "<td>" + json_data[i]["nom"] + " (" + json_data[i]["num"] + ")</td>"
			+ "<td>" + json_data[i]["date"].split(" ")[1] + "</td>"
			+ "<td>" + json_data[i]["destination"] + "</td>"
			+ "</tr>";
		html += "<tr class=\"collapse out budgets\" id=\"tr_form_new_bet_" + i + "\" data-sation_uic=\"\" data-train_num=\"\">"
			+ "<td colspan=\"4\">";
		
		$.ajax({
			url: "form/form_new_bet.jsp",
			async: false,
			dataType: "html",
			type: "get",
			error: function(xhr, ajaxOptions, thrownError) {
				alert("error search_train_display\n" + xhr.status + "\n" + thrownError);
			},
			success: function(content) {
				html += content;
			}
		});
		
		html += "</td>"
			+ "</tr>";
	}
	$("#table_search_train>tbody").html(html);*/
	
	return true;
}



/**
 * Recherche les utilisateurs par pseudo.
 */
function form_search_user() {
	$.ajax({
		url: "S_SearchUser",
		async: true,
		data: {
			pseudo: $("#form_search_user_pseudo").val()
		},
		dataType: "json",
		type: "post",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Erreur recherche utilisateur\n" + xhr.status + "\n" + thrownError);
		},
		success: function(content) {
			form_search_user_display(content);
		}
	});
	
	return false;
}

/**
 * Affiche les utilisateurs.
 */
function form_search_user_display(json_data) {
	var html = "";
	for(i = 0, i_max = objectLength(json_data); i < i_max; i++) {
		//TODO
		html += "<tr>"
			+ "<td><span class=\"glyphicon glyphicon-heart\"></span></td>"
			+ "<td>" + json_data[i]["pseudo"] + "</td>"
			+ "<td>" + json_data[i]["score"] + "</td>"
			+ "<td>" + (json_data[i]["nb_paris_justes"] * 100 / json_data[i]["nb_paris_total"]).toFixed(2) + " %</td>"
			+ "</tr>";
	}
	$("#table_search_user>tbody").html(html);
	
	return true;
}






/**
 * Recherche les amis.
 */
function friends(id) {
	$.ajax({
		url: "S_Friends",
		async: true,
		data: {
			id: id
		},
		dataType: "json",
		type: "get",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("Erreur friends\n" + xhr.status + "\n" + thrownError);
		},
		success: function(content) {
			friends_display(content);
		}
	});
	
	return false;
}

/**
 * Affiche les amis.
 */
function friends_display(json_data) {
	var html = "";
	for(i = 0, i_max = objectLength(json_data); i < i_max; i++) {
		html += "<tr>"
			+ "<td><span class=\"glyphicon glyphicon-remove\"></span></td>"
			+ "<td>" + json_data[i]["pseudo"] + "</td>"
			+ "<td>" + json_data[i]["score"] + "</td>"
			+ "<td>" + (json_data[i]["nb_paris_justes"] * 100 / json_data[i]["nb_paris_total"]).toFixed(2) + " %</td>"
			+ "</tr>";
	}
	$("#table_friends>tbody").html(html);
	
	return true;
}



/**
 * Recherche les amis.
 */
function challenges(id) {
	// TODO
	/*var data;
	$.ajax({
		url: "/Challenges",
		async: true,
		data: {
			id: id
		},
		dataType: "json",
		type: "get",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("error challenges\n" + xhr.status + "\n" + thrownError);
		},
		success: function(content) {
			challenges_display(content);
		}
	});
	
	return false;*/
	var json = [];
	for(var i = 0; i < 2; i++) {
		json.push({id_defi: 123456, opponent_pseudo: "Emile", opponent_duration: 12, opponent_bet: 150, self_duration: 0, self_bet: 0, train: "SARA", station: "Austerlitz", destination: "Saint-Quentin en Yvelines", date: "9:36"});
		json.push({id_defi: 123456, opponent_pseudo: "Franz", opponent_duration: 0, opponent_bet: 0, self_duration: 10, self_bet: 999, train: "DEFI", station: "Versailles Chantiers", destination: "La Défense Grande Arche", date: "10:54"});
	}
	return challenges_display(json);
}

/**
 * Affiche les amis.
 */
function challenges_display(json_data) {
	var html = "";
	var i_max = objectLength(json_data);
	if(i_max == 0) {
		html += "<tr class=\"info\"><td colspan=\"\">Il n'y a pas de défis à afficher.</td></tr>"
	}
	else {
		for(var i = 0; i < i_max; i++) {
			html += "<tr" + (json_data[i]["self_duration"] == 0 ? " class=\"danger\"" : "") + ">"
				+ "<td>" + json_data[i]["opponent_pseudo"] + "<br/>" + (json_data[i]["opponent_duration"] > 0 ? json_data[i]["opponent_bet"] + " pts sur " + json_data[i]["opponent_duration"] + "min" : "en attente") + "</td>"
				+ "<td>" + (json_data[i]["self_duration"] > 0 ? json_data[i]["self_bet"] + " pts sur " + json_data[i]["self_duration"] + "min" : "en attente") + "</td>"
				+ "<td>" + json_data[i]["station"] + "</td>"
				+ "<td>" + json_data[i]["train"] + " de " + json_data[i]["date"] + "<br/>" + json_data[i]["destination"] + "</td>"
				+ "<td>" + (json_data[i]["self_duration"] == 0 ? challenges_form() : "") + "</td>"
				+ "</tr>";
		}
	}
	$("#table_challenges>tbody").html(html);
	
	return true;
}

/**
 * Récupère le formulaire de réponse à un défi.
 */
function challenges_form() {
	var html = "";
	
	$.ajax({
		url: "form/form_challenge_response.jsp",
		async: false,
		dataType: "html",
		type: "get",
		error: function(xhr, ajaxOptions, thrownError) {
			alert("error challenges_form\n" + xhr.status + "\n" + thrownError);
		},
		success: function(content) {
			html += content;
		}
	});
	
	return html;
}